package com.xiaoyang.common.core.utils;

import cn.hutool.core.lang.UUID;
import com.xiaoyang.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /**
     * ⽣成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
        return token;
    }

    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private static String toStr(Object value) {
        if (value == null) {
            return "";
        }
        return value.toString();
    }

    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_KEY));
    }

    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_ID));
    }

    public static void main(String[] args) {
//        Map<String, Object> claims = new HashMap<>();
//        String userKey = UUID.fastUUID().toString();
//        claims.put(JwtConstants.LOGIN_USER_ID, 1L);
//        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
//        String token = JwtUtils.createToken(claims, "yskzdd");// secret: 保密 随机 定期更换
//        System.out.println(token);
//        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEsInVzZXJLZXkiOiJjZjY3NDcxYS02N2EzLTRhYjctOTkzYi00MDA5OGU0YzllYTgifQ.m54o52WIQNED1NYB1kJH7ThR1YgUSlWjvEpXhcrgjBy6eFg36moQ6ERokyPaCgOKnmEk7sSZNjwbF3FyVo6K9A";
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEsInVzZXJLZXkiOiJhNTBlNDU3Zi1jZGI5LTQ4NTAtOTRmMC1lMzU5ZTI2MzY4NWYifQ.VW33CW-tLlbrm3ZEZYkJ3TqgoSehhfazORLAY4VOuNHzW2dUuHCyeduHqogaNzpMB-rP3KUU2WhzUGp6TK4dCQ";
        Claims claims = parseToken(token, "yskzdd");
        System.out.println(claims);
    }
    public static void main1(String[] args) {
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("userId", 123456L);

//        System.out.println(createToken(claims, "qwertyuio"));
        String str = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEsInVzZXJLZXkiOiJmZTA2YTE1ZC04ZmM0LTRmNTItOWJiYi04OWFmOGQ2Y2E3MmUifQ.y2bGY59DGSCOXvrTCasdwCl8BdSYqTpKcwNBddP6Xgc5AUszLkUa7uyVOAIdmRWfyuo2xVFmiZ_t89pzWCmEvg";

        System.out.println(parseToken(str, "yskzdd"));

        // 1. 用户登录成功后,调用createToken() 生成令牌 并发送客户端
        // 2. 后续的所有请求,再调用具体的接口之前, 都要通过token验证身份
        // 3. 用户使用过程中需要再适合的时间延长jwt的过期时间
    }
}
